package UI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.WindowConstants;

import data_management.InvDBManager;
import data_management.PermissionManager;

/**
 * This class is used for adding items to the inventory.
 * @author NewBird
 *
 */
public class AddItemDialog extends JDialog implements ActionListener {

	private static final int WIDTH = 480;
	private static final int HEIGHT = 480;

	private JPanel mPanel;

	private Vector<JTextField> fields;
	private Vector<JLabel> labels;
	private Vector<String> columns;

	/*@ 
	  @ ensures fields != null;
	  @ ensures labels != null;
	  @ ensures columns != null;
	  @ ensures mPanel != null;
	  @ assignable fields;
	  @ assignable labels;
	  @ assignable columns;
	  @ assignable mPanel;
	  @ 
	 @*/
	public AddItemDialog() {

		columns = InvDBManager.getInstance().getColumns("inventory");

		setModalityType(ModalityType.APPLICATION_MODAL);
		mPanel = new JPanel();
		mPanel.setLayout(new GridLayout(columns.size() + 1, 2));
		add(mPanel);



		fields = new Vector<JTextField>();
		labels = new Vector<JLabel>();

		for (int i = 0; i < columns.size(); i++) {
			labels.add(new JLabel(columns.get(i) + ":  "));
			//labels.get(i).setMinimumSize(new Dimension(0, fields.get(i).getHeight()));
			labels.get(i).setAlignmentX(RIGHT_ALIGNMENT);
			mPanel.add(labels.get(i));

			fields.add(new JTextField(15));
			fields.get(i).setMinimumSize(new Dimension(100, 25));
			fields.get(i).setMaximumSize(new Dimension(100, 25));
			fields.get(i).setAlignmentX(LEFT_ALIGNMENT);
			mPanel.add(fields.get(i));
		}

		// add a blank label and our button
		JLabel blank = new JLabel();
		mPanel.add(blank);
		JButton okButton = new JButton("Ok");
		okButton.addActionListener(this);
		mPanel.add(okButton);

		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		setPreferredSize(new Dimension(WIDTH, columns.size() * 30));
		setResizable(false);
		pack();
		setVisible(true);
	}

	/**
	 * This method adds the new item to the database.
	 */
	/*@ 
	  @ requires InvDBManager.getInstance() != null;
	  @ 
	 @*/
	public void addItem() {
		Vector<String> values = new Vector<String>();

		for (int i = 0; i < fields.size(); i++) {
			values.add(fields.get(i).getText());
		}

		InvDBManager.getInstance().addItem(values, PermissionManager.getInstance().desktopUser);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		addItem();
		setVisible(false);
		InventoryInterface.getInstance().performSearch();
	}

}
